	package com.ibeetl.eval.worker;

import java.util.Map;

import org.beetl.core.GroupTemplate;
import org.beetl.core.exception.ScriptEvalError;
import org.jdom2.Element;

import com.ibeetl.eval.EvalContext;
import com.ibeetl.eval.NodeWorker;
import com.ibeetl.eval.TreeNode;
import com.ibeetl.eval.XmlEvalException;

public class ExpressNodeWorker implements NodeWorker {

	public  TreeNode execute(Element ruleEle,EvalContext ctx){
		
		String name = ruleEle.getAttributeValue("name");//simple exression
		String express = ruleEle.getText();
		//计算表达式结果
		Map paras = ctx.prepareNext();
		TreeNode node = ctx.goNext(name, ruleEle);
		paras.put("_root", node);
		Object ret = runExpress(ctx,ruleEle,express,paras);
		node.setResult(ret);
		return node;
	}
	private Object runExpress(EvalContext ctx,Element location,String script,Map<String,Object> paras) {
		String express = "return "+script+";";
		GroupTemplate gt = ctx.getEvalEngine().gt;
		try {
			Map map= gt.runScript(express, paras);
			return map.get("return");
		} catch (ScriptEvalError e) {
			
			throw new XmlEvalException(location,e); 
		}
		
	}
	


}
